package com.jzbooks.handler;

import com.alibaba.fastjson.JSONObject;
import com.jzbooks.result.ErrorResult;
import com.jzbooks.result.PlatformResult;
import com.jzbooks.utils.SpringUtil;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;


/**
 * @author mingPeng
 * @date 2021/4/19 18:34
 * @Description :  返回数据处理器，封装全局的返回数据
 */
@RestControllerAdvice
public class ResponseResultHandler implements ResponseBodyAdvice<Object> {

    //判断是否要执行beforeBodyWrite方法，true为执行，false不执行
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        //再request的请求头里取值，判断是否是swagger请求
        String whetherSwagger = SpringUtil.getRequest().getHeader("whetherSwagger");

        //判断方法的返回值
        return  whetherSwagger!=null;
    }
    
    @Override
    public Object beforeBodyWrite(Object body
            , MethodParameter returnType
            , MediaType selectedContentType
            , Class<? extends HttpMessageConverter<?>> selectedConverterType
            , ServerHttpRequest request
            , ServerHttpResponse response) {

        if (body instanceof ErrorResult){
            return ErrorResult.failure((ErrorResult) body);
        }else if (body instanceof String){
            return PlatformResult.success(body);
        } else{
            return PlatformResult.success(body);
        }
    }
}
